package cn.com.shadowless.xinning.view.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mengpeng.mphelper.ToastUtils;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.GeneralOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;

/**
 * The type General fragment.
 *
 * @author sHadowLess
 */
public class GeneralFragment extends BaseFragment {

    /**
     * The General receipt info receipt num.
     */
    @BindView(R.id.general_receiptInfo_ReceiptNum)
    TextView generalReceiptInfoReceiptNum;
    /**
     * The General receipt info making depart.
     */
    @BindView(R.id.general_receiptInfo_MakingDepart)
    TextView generalReceiptInfoMakingDepart;
    /**
     * The General receipt info position job.
     */
    @BindView(R.id.general_receiptInfo_PositionJob)
    TextView generalReceiptInfoPositionJob;
    /**
     * The General app form info reimburse way.
     */
    @BindView(R.id.general_appFormInfo_ReimburseWay)
    TextView generalAppFormInfoReimburseWay;
    /**
     * The General app form info payer.
     */
    @BindView(R.id.general_appFormInfo_Payer)
    TextView generalAppFormInfoPayer;
    /**
     * The General app form info position.
     */
    @BindView(R.id.general_appFormInfo_Position)
    TextView generalAppFormInfoPosition;
    /**
     * The General app form info depart pay.
     */
    @BindView(R.id.general_appFormInfo_DepartPay)
    TextView generalAppFormInfoDepartPay;
    /**
     * The General app form info currency.
     */
    @BindView(R.id.general_appFormInfo_Currency)
    TextView generalAppFormInfoCurrency;
    /**
     * The General app form info payment method.
     */
    @BindView(R.id.general_appFormInfo_PaymentMethod)
    TextView generalAppFormInfoPaymentMethod;
    /**
     * The General app form info in reimbursement.
     */
    @BindView(R.id.general_appFormInfo_InReimbursement)
    TextView generalAppFormInfoInReimbursement;
    /**
     * The General app form info attachment num.
     */
    @BindView(R.id.general_appFormInfo_AttachmentNum)
    TextView generalAppFormInfoAttachmentNum;
    /**
     * The Ms tab.
     */
    @BindView(R.id.ms_tab)
    LinearLayout msTab;
    /**
     * The General check process.
     */
    @BindView(R.id.general_check_Process)
    LinearLayout generalCheckProcess;
    /**
     * The General order amount.
     */
    @BindView(R.id.general_orderAllAmount)
    TextView generalOrderAllAmount;
    /**
     * The General with tax amount.
     */
    @BindView(R.id.general_withTaxAmount)
    TextView generalWithTaxAmount;
    /**
     * The General without tax amount.
     */
    @BindView(R.id.general_withoutTaxAmount)
    TextView generalWithoutTaxAmount;
    /**
     * The General remark.
     */
    @BindView(R.id.general_remark)
    TextView generalRemark;

    private final String forMatString = "%s\n公司预算金额：%s\n已报销：%s\n报销中：%s\n剩余可报销：%s\n已申请未报销：%s\n在申请未报销：%s\n剩余可申请：%s";
    private final String url = "api/GeneralExpandForm/LoadCheckHistoryList?%s=";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_general_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initGeneralOrderInfoData(orderId, userName);
            initCheckHistoryList(String.format(url, "orderId") + orderId, mActivity, generalCheckProcess);
        }
    }

    @Override
    protected void initView() {

    }

    private void initGeneralOrderInfoData(String orderId, String userName) {
        OrderPresenter.getSingleton().getGeneralOrderInfo(orderId, userName, new RequestCallBack<GeneralOrderInfo>() {
            @Override
            public void success(RequestResult<GeneralOrderInfo> result) {
                String token = result.getLoginToken();
                String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                if (result.isSucceed() && null != result.getResult()) {
                    if (null != token && token.equals(oldToken)) {
                        Log.e(TAG, "success: " + result.toString());
                        GeneralOrderInfo.DataBean dataBean = result.getResult().getData();
                        GeneralOrderInfo.DataBean.CreateUserObjectBean userObjectBean = dataBean.getCreateUserObject();
                        GeneralOrderInfo.DataBean.CreateUserObjectBean.PayToUserObjectBean payToUserObjectBean = dataBean.getPayToUserObject();
                        List<GeneralOrderInfo.DataBean.CreateUserObjectBean.PayToUserObjectBean.ExpandApplyListBean> expandApplyListBeans = dataBean.getExpandApplyList();

                        String formNum = dataBean.getFormNum();
                        String departName = userObjectBean.getDepartmentName();
                        String positionName = userObjectBean.getPositionName();

                        boolean expendType = dataBean.isExpendType();
                        String payUser = payToUserObjectBean.getUserName();
                        String payDepartName = dataBean.getPayDepartName();
                        String currency = dataBean.getCurrency();
                        String payment = dataBean.getPayment();
                        String expendMonth = dataBean.getExpendMonth();
                        String appendixNum = dataBean.getAppendixNum() + "";
                        generalAppFormInfoPayer.setText(payUser);
                        generalAppFormInfoPosition.setText(positionName);
                        generalAppFormInfoDepartPay.setText(payDepartName);
                        generalAppFormInfoCurrency.setText(currency);
                        generalAppFormInfoPaymentMethod.setText(payment);
                        generalAppFormInfoInReimbursement.setText(expendMonth);
                        generalAppFormInfoAttachmentNum.setText(appendixNum);
                        if (expendType) {
                            generalAppFormInfoReimburseWay.setText("否");
                        } else {
                            generalAppFormInfoReimburseWay.setText("是");
                        }

                        for (GeneralOrderInfo.DataBean.CreateUserObjectBean.PayToUserObjectBean.ExpandApplyListBean expandApplyListBean : expandApplyListBeans) {
                            View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_general_tab_item, null, false);
                            LinearLayout tab = view.findViewById(R.id.tab_item);

                            LinearLayout originOrder = view.findViewById(R.id.OriginOrder);
                            LinearLayout makeTime = view.findViewById(R.id.MakeTime);
                            LinearLayout applier = view.findViewById(R.id.Applier);
                            TextView generalDetailMakeTime = view.findViewById(R.id.general_detail_MakeTime);
                            TextView generalDetailOriginOrder = view.findViewById(R.id.general_detail_OriginOrder);
                            TextView generalDetailApplier = view.findViewById(R.id.general_detail_Applier);
                            TextView generalDetailBudget = view.findViewById(R.id.general_detail_Budget);
                            TextView generalDetailInvoiceAmount = view.findViewById(R.id.general_detail_InvoiceAmount);
                            TextView generalDetailReimbursableWithAmount = view.findViewById(R.id.general_detail_ReimbursableWithAmount);
                            TextView generalDetailReimbursableWithoutAmount = view.findViewById(R.id.general_detail_ReimbursableWithoutAmount);
                            TextView generalDetailApplyYear = view.findViewById(R.id.general_detail_ApplyYear);
                            TextView generalDetailInvoiceNumber = view.findViewById(R.id.general_detail_InvoiceNumber);
                            TextView generalDetailInvoiceType = view.findViewById(R.id.general_detail_InvoiceType);
                            TextView generalDetailDigest = view.findViewById(R.id.general_detail_Digest);
                            TextView generalDetailAttachmentNum = view.findViewById(R.id.general_detail_AttachmentNum);
                            TextView generalDetailBudgetaryState = view.findViewById(R.id.general_detail_BudgetaryState);


                            String applyId = expandApplyListBean.getApplyId();
                            if (null != applyId && !"".equals(applyId)) {
                                originOrder.setVisibility(View.VISIBLE);
                                generalDetailOriginOrder.setText(applyId);
                                GeneralOrderInfo.DataBean.CreateUserObjectBean.PayToUserObjectBean.ExpandApplyListBean.PayObjectBean payObjectBean = expandApplyListBean.getPayObject();
                                if (null != payObjectBean) {
                                    String createUserName = payObjectBean.getCreateUserName();
                                    String createTimeStr = payObjectBean.getCreateTimeStr();
                                    if (null != createTimeStr && !"".equals(createTimeStr)) {
                                        makeTime.setVisibility(View.VISIBLE);
                                        generalDetailMakeTime.setText(createTimeStr);
                                    } else {
                                        makeTime.setVisibility(View.GONE);
                                    }
                                    if (null != createUserName && !"".equals(createUserName)) {
                                        applier.setVisibility(View.VISIBLE);
                                        generalDetailApplier.setText(createUserName);
                                    } else {
                                        applier.setVisibility(View.GONE);
                                    }
                                } else {
                                    applier.setVisibility(View.GONE);
                                }
                            } else {
                                originOrder.setVisibility(View.GONE);
                            }

                            GeneralOrderInfo.DataBean.CreateUserObjectBean.PayToUserObjectBean.ExpandApplyListBean.BudgetInfoObjectBean budgetInfoObjectBean = expandApplyListBean.getBudgetInfoObject();
                            String budgetName = expandApplyListBean.getBudgetName();
                            String invoiceNum = expandApplyListBean.getInvoiceNum();
                            String invoiceValue = getDecimal(expandApplyListBean.getInvoiceValue().doubleValue());
                            String expendWithDuty = getDecimal(expandApplyListBean.getExpendWithDuty().doubleValue());
                            String expendWithOutDuty = getDecimal(expandApplyListBean.getExpendWithOutDuty().doubleValue());
                            String expendYear = expandApplyListBean.getExpendYear();
                            String invoiceType = expandApplyListBean.getInvoiceType();
                            String remark = expandApplyListBean.getRemark();
                            String appendixNum1 = dataBean.getAppendixNum() + "";
                            String explain = String.format(forMatString,
                                    budgetInfoObjectBean.getBudgetInfo(),
                                    getDecimal(budgetInfoObjectBean.getAllMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getReimbursedMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getReimbursingMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getRemainReimburseMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getApplyedMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getApplyingMoney().doubleValue()),
                                    getDecimal(budgetInfoObjectBean.getRemainApplyMoney().doubleValue())
                            );
                            generalDetailInvoiceNumber.setText(invoiceNum);
                            generalReceiptInfoReceiptNum.setText(formNum);
                            generalReceiptInfoMakingDepart.setText(departName);
                            generalReceiptInfoPositionJob.setText(positionName);

                            generalDetailBudget.setText(budgetName);
                            generalDetailInvoiceAmount.setText(invoiceValue);
                            generalDetailReimbursableWithAmount.setText(expendWithDuty);
                            generalDetailReimbursableWithoutAmount.setText(expendWithOutDuty);
                            generalDetailApplyYear.setText(expendYear);
                            generalDetailInvoiceType.setText(invoiceType);
                            generalDetailDigest.setText(remark);
                            generalDetailAttachmentNum.setText(appendixNum1);
                            generalDetailBudgetaryState.setText(explain);

                            msTab.addView(tab);
                        }

                        String totalBill = getDecimal(dataBean.getTotalBill().doubleValue());
                        String expendAmountWithDuty = getDecimal(dataBean.getExpendAmountWithDuty().doubleValue());
                        String expendAmountWithOutDuty = getDecimal(dataBean.getExpendAmountWithOutDuty().doubleValue());
                        String remark = dataBean.getRemark();
                        generalOrderAllAmount.setText(totalBill);
                        generalWithTaxAmount.setText(expendAmountWithDuty);
                        generalWithoutTaxAmount.setText(expendAmountWithOutDuty);
                        generalRemark.setText(remark);
                    } else {
                        ToastUtils.onErrorShowToast("登录态与服务器不一致");
                        initLogoutInfo(mActivity, userName);
                    }
                } else {
                    ToastUtils.onErrorShowToast("该订单暂无详细信息");
                }
            }

            @Override
            public void fail(String errorMsg) {
                ToastUtils.onErrorShowToast(errorMsg);
            }
        });
    }
}
